/**
 * 比多赢文本编辑器
 */
var ueEditor = new function () {
	/**
	 * 图片管理插件UI
	 */
	var editorPlugins = {
	    btnImg : {
            c:'xheIcon xheBtnImg', 
			t:'插入图片', 
			h:0, 
			e: function() {	
			    var _this=this;			
			    var html = '';
					html += '<div id="bd-uploader">'
					html += '	<div class="flash" id="fsUploadProgress"></div>'
					html +=	'   <div id="buttonArea">'
					html +=	'       <input class="fl" type="checkbox" name="select-all-pic" id="select-all-pic" />'
					html +=	'       <a href="javascript:void(0);" id="get-pics" class="up-btn fl" title="点击这里把选中的图片插入到编辑器中"><span><div id="div-get-pics">引用图片</div></span></a>'
					html +=	'       <a href="javascript:void(0);" id="addFiles" class="up-btn fl" title="点击这里上传图片"><span><div id="divAddFiles">添加文件</div></span></a>'
					html +=	'       <a href="javascript:void(0);" class="img-by-owner">我的图片</a>'
					html +=	'       <a href="javascript:void(0);" class="img-by-owner current">全部图片</a>'
					html +=	'   </div>'
					html +=	'   <div id="photo-list">'
					html +=	'       <span class="fl note" style="padding:0 0 0 10px;">1.双击图片把该图片插入编辑器； 2.单击选中图片后点击"引用图片"把选中的图片插入编辑器中。 </span>'
					html +=	'       <ul><div class="floor-loading"></div></ul>'
					html +=	'   </div>'
					html +=	'   <div id="photo-paging">'
					html +=	'     <a href="javascript:;">头页</a>'
					html +=	'     <a href="javascript:;">上一页</a>'
					html +=	'     <a href="javascript:;">1</a>'
					html +=	'     <a href="javascript:;">2</a>'
					html +=	'     <a href="javascript:;">3</a>'
					html +=	'     <a href="javascript:;">4</a>'
					html +=	'     <a href="javascript:;">下一页</a>'
					html +=	'     <a href="javascript:;">尾页</a>'
					html +=	'   </div>'
					html +=	'</div>';

			    creatPopBox('', 685, 432, html);
			
				var editorSwfu;
				//$(function() {					
				var settings = {
					flash_url : ctx+"js/uploader/swfupload.swf",
					upload_url: ctx+"index.php?app=system&ctl=uploader&act=add&ajax=1",
					post_params: {"UESID" : getCookie("UESID")}, // json格式
					file_size_limit : "500 K",
					file_types : "*.jpg;*.gif;*.png",		
					file_types_description : "图片",
					file_upload_limit : 12,
					file_queue_limit : 0,
					file_post_name : 'file',
					custom_settings : { progressTarget : "fsUploadProgress"},
					
					debug: false,
			
					// Button settings
					button_image_url: "js/uploader/images/add.gif",
					button_width: 80,
					button_height: 17,
					button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
					button_cursor: SWFUpload.CURSOR.HAND,
					button_placeholder_id: "divAddFiles",
					button_text: '<span class="theFont">上传图片</span>',
					button_text_style: ".theFont {color:#006699; }",
					button_text_left_padding: 20,
					button_text_top_padding: 0,
					
					// The event handler functions are defined in handlers.js
					file_queued_handler : fileQueued,
					file_queue_error_handler : fileQueueError,
					file_dialog_complete_handler : fileDialogComplete,
					upload_start_handler : uploadStart,
					upload_progress_handler : uploadProgress,
					upload_error_handler : uploadError,
					upload_success_handler : _this.uploadFinishHandler,
					upload_complete_handler : uploadComplete,
					queue_complete_handler : queueComplete
				};
				
				//$('body').html(settings.upload_url);
				editorSwfu = new SWFUpload(settings);
				 //});
	
				//alert(settings.post_params.UESID);
				$.ajaxf.ready(function(){
					//var r = {'Err':true, '':'yy'};
					//_this.showPhotos({a:'xx', b:'s'});
					//return;
					// TODO 服务器端				
					var imgLibUri = ctx+"index.php?app=system&ctl=uploader&act=list&ajax=1&"+Math.random();
					
					$.ajaxf.postJSON(imgLibUri, '', function(r){						
						_this.showPhotos(r);
						_this.showPaging(1, r);
						return;
					});
				});
					
				_this.uploadFinishHandler = function (file, r) {
					//alert(r);
					//alert(file);
					eval('var r = ' + r);
					html = '<li class="checked" id="photo-list-item-'+file.id+'">'
						 + '  <input class="check-pic" type="checkbox" name="check-pic[]" value="' + file.id +'" checked="checked" />'
						 + '  <input type="hidden" class="checked-pic-src" id="checked-pic-src-'+file.id+'" value="' + r['img']+'" />'
						 + '  <p><img class="pic" src="'+ r['thumb'] + '" ></p>'
						 + '  <p id="checked-pic-title-'+file.id+'" class="pic-title">'+r['title']+'</p>'
						 + '</li>';
					$('#photo-list ul').prepend(html);
				}
				
				/**
				 * 显示分页
				 */
				_this.showPaging = function (page, r) {
					var paging = '';
					paging += "<a href=\"javascript:;\" page=\"1\">[头页]</a>";
					paging += "<a href=\"javascript:;\" page=\""+pagingPre+"\">[上一页]</a>";
					
					var pagingFirst = page - 5;
					var pagingLast  = page + 5;
					var pagingPre   = page - 1;
					var pagingNext  = page + 1;
					
					if(pagingFirst < 1) pagingFirst = 1;
					if(pagingPre < 1) pagingPre = 1;
					if(pagingLast > r.pages) pagingLast = r.pages;
					if(pagingNext > r.pages) pagingNext = r.pages;
					
					for(var i = pagingFirst; i <= pagingLast; i++) {
						var current = '';
						if(i == page) current = 'class="current"';
						paging += "<a href=\"javascript:;\" page=\""+i+"\" "+current+">["+i+"]</a>";
						current = '';
					}
					
					paging += "<a href=\"javascript:;\" page=\""+pagingNext+"\">[下一页]</a>";
					paging += "<a href=\"javascript:;\" page=\""+r.pages+"\">[尾页]</a>";
					paging += ' 共'+r.pages+'页,'+r.totals+'张';
					
					$('#photo-paging').html(paging);
					$('#photo-paging a').click(function() {_this.loadPage($(this).attr('page'));});
				}
				
				_this.loadPage = function (page) {
					var url = ctx+"index.php?app=system&ctl=uploader&act=list&ajax=1&page="+page;
					$('#photo-list ul').html('<div class="floor-loading"></div>');
					$.ajaxf.postJSON(url, '', function(r){						
						_this.showPhotos(r);
						_this.showPaging(page, r);						
					});
				}
				
				
				/**
				 * 显示已上传的图片
				 */
				_this.showPhotos = function (r) {
					if(r.err) {
						// 没有权限则转到登录页
						if('denned' == r.err) {
							parent.window.location=''; // 转到登录页
							return;
						}
						
						// 显示错误信息
						$('#photo-list ul').html('<p class="err">'+r.err+'</p>');
						return;
					}
					
					var html = '';
					var imgs = r.imgs;
					if(imgs.length <= 0) {
						html += '<p id="no-upload-pic">您还没有上传图片！</p>';
					} else {
						html = '';
						for(var i in imgs) {
							html += '<li id="photo-list-item-'+i+'">'
								  + '  <input class="check-pic" type="checkbox" name="check-pic[]" value="' + i +'" />'
								  + '  <input type="hidden" class="checked-pic-src" id="checked-pic-src-'+i+'" value="' + imgs[i]['img']+'" />'
								  + '  <p><img class="pic" src="'+ imgs[i]['thumb'] + '" ></p>'
								  + '  <p id="checked-pic-title-'+i+'" class="pic-title">'+imgs[i]['title']+'</p>'
								  + '</li>';
						}
						
					}
					
					//alert(html);
					$('#photo-list ul').html(html);
					
					// 点击图片选中
					$('#photo-list img').click(function(){
						if($(this).parent().parent().hasClass('checked')) {
							$(this).parent().parent().find('input').removeAttr('checked', 'checked');
							$(this).parent().parent().removeClass('checked');
						} else {
							$(this).parent().parent().find('input').attr('checked', 'checked');
							$(this).parent().parent().addClass('checked');
						}
					});
					
					$('#photo-list img').dblclick(function(){
						var parent = $(this).parent().parent();
						var src = parent.find('.checked-pic-src').attr('value');
						var title = parent.find('.pic-title').text();						
						_this.pasteHTML('<img src="'+src+'" alt="'+title+'" />');
						removePopBox();
					});
					
					// 添加和去掉被选中状态样式
					$('#photo-list input').click(function(){
						var li = $(this).parent();
						if(li.hasClass('checked')) {
							li.removeClass('checked');
						} else {
							li.addClass('checked');
						}
					});
					
					// 选中或去掉所有选择的图片
					$('#bd-uploader #select-all-pic').click(function(){
						if(!$(this).attr('checked')) {
							$('#photo-list input').removeAttr('checked')
							$('#photo-list li').removeClass('checked')
						} else {
							$('#photo-list input').attr('checked', 'checked')
							$('#photo-list li').addClass('checked')
						}
					});
				
					$('#get-pics').click(function(){
						var pics = new Array();
						var obj = $('#photo-list input.check-pic:checked');
						if(obj.length <= 0) {
							//alert('请选择图片');
							return;
						}
						
						var html = '';
						for(var i = 0; i< obj.length; i++) {
							//var pic = new Object();
							var src = $('#checked-pic-src-'+obj[i].value).attr('value');
							var title = $('#checked-pic-title-'+obj[i].value).text();
							//pics.push(pic);
							html += '<img src="'+src+'" alt="'+title+'" /><br />';
						}
						
						_this.pasteHTML(html);
						removePopBox();
			
					});
				}
	        }
		}
	}
	// End 图片管理插件UI
	
	var editorOption = {
		//upImgUrl:'!{editorRoot}xheditor_plugins/multiupload/multiupload.html',
		//upImgExt:"jpg,jpeg,gif,png",
		//skin:'nostyle',
		skin:'o2007blue',
		//skin:'vista',
		plugins:editorPlugins,
		tools:'Pastetext,|,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,Removeformat,|,Align,List,Outdent,Indent,|,Link,Unlink,|,btnImg,Media,Flash,Table,|,Source,|,About'};
	
	this.apply = function (id, lang){
		if(typeof lang == 'undefined') var lang ='zh-cn';
		if(typeof ctx == 'undefined') var ctx ='/';
		//alert(ctx);
		// 调用 swfupload 上传组件
		// TODO 合并当前导入的文件
		document.write(unescape('%3Cscript type="text/javascript" src="'+ctx+'js/uploader/swfupload.js"%3E%3C/script%3E'));	
		document.write(unescape('%3Cscript type="text/javascript" src="'+ctx+'js/uploader/queue.js"%3E%3C/script%3E'));	
		document.write(unescape('%3Cscript type="text/javascript" src="'+ctx+'js/uploader/fileprogress.js"%3E%3C/script%3E'));	
		document.write(unescape('%3Cscript type="text/javascript" src="'+ctx+'js/uploader/handlers.js"%3E%3C/script%3E'));	
		document.write(unescape('%3Cscript type="text/javascript" src="'+ctx+'js/uploader/lang/'+lang+'.js"%3E%3C/script%3E'));
		
		return $(id).xheditor(editorOption);
	}
}

